/**
 * @author Adnane Tellou
 *
 * January 7th 2013 *
 */
jQuery(document).ready(function($){

    $.ajaxSetup({ async : false });

    //------------------------------------------------ FUNCTIONS ---------------------------------------------------//
    // Fills the table with nxn cells, in this case n=5 ; also defines some listeners
    function rendertable(){
        var table = $("#gametb");
        var content="";
        for(i=0; i<5; i++){
            content+="<tr>";
            for(j=0; j<5; j++){
                var idc= ''+i+j;
                content+='<td> <div type="button" id='+idc+' value="" class="cellen"></div></td>';
            }
            content+="</tr>";
        }
        table.append(content);
        $('.cellen').live('click',function(){
            showCellEditor($(this));
        });
        $('#commitword').live('click',function(){
            playTurn();
        });
        $('#cancelword').live('click',function(){
            $('#finalword').text("");
            setSelectableCells();
            selectedCells=new Array();
            lastselectedcell=null;
        });
        $('#reset').live('click',function(){
            $('#wordoutput').hide(1000);

            setuptable();
        });
        $('#skip').live('click',function(){
            skipTurn();
        });
    }

    // Gets the state of the table from the controller and reflects it on the view does the same with the score
    function setuptable(){
        lastselectedcell=null;
        // SCAN FOR CELLS TO GET STATE AND SET EACH ONE TO IT'S STATE (uses server)
        // GET SCORES AND SHOW THEM OUT
        $('#errormsg2').text("");
        $('#skip').show(1000);
        $.getJSON("/game", {id : room_number, req : "get_player",player_name:player},function(pl){
            $("#score1").text(pl.score);});
        console.log(player2+" is gamer2");
        $.getJSON("/game", {id : room_number, req : "get_player",player_name:player2},function(pl){
            $("#score2").text(pl.score);});
        for(i=0;i<5;i++){
            for(j=0;j<5;j++){
                var idc = "#"+i+j;
                var letter;
                var activ;
                $.getJSON("/game",{id : room_number, req : "get_cell",x:i,y:j},
                 function(cell){
                    
                    letter = cell.letter;
                    activ = cell.isActivated;

                    var cellule= $(idc);
                    cellule.text(letter.toUpperCase());
                    if(activ){enableCell(cellule);}else{disableCell(cellule);}
                    });
            }
        }

    }

    // Initializing the game consists of calling the previous method and do some UI tasks
    function initgame(){
        setuptable();
        $("#wait").hide(2000);
        $("#players").show(1000);
        $("#gamezone").show(1000);

    }

    // Some other utils for cells, lets us disable or enable cells controlling their class attribute
    function disableCell(cell){
        cell.removeClass('cellen').removeClass('cellsel').addClass('celldis');
    }
    function enableCell(cell){
        cell.removeClass('celldis').removeClass('cellsel').addClass('cellen');
    }
    function disableTable(){
        for(i=0;i<5;i++){
            for(j=0;j<5;j++){
                idc = "#"+i+j;
                disableCell($(idc));
            }
        }
    }

    // Shows the cell editor, let's us insert a letter into the caller Cell
    function showCellEditor(cell){
            // only letters are allowed
        var pattern=new RegExp("[a-zA-Z]","i");
        $('#celledit').show(1000);
        $('#setcell').die();
        $('#setcell').live('click',function(){
                if(pattern.test($('#lettertocell').val())){
                    cell.text($('#lettertocell').val().toUpperCase());
                    $('#lettertocell').val("");
                    $('#celledit').hide(1000);
                    disableCell(cell);
                    lastEditedCell=cell;
                    $('#errormsg').text("");
                    startSelectionMode();
                }else{
                    $('#errormsg').text("Please insert a LETTER!");
                }
        });
    }
    //ENTER TO WORD SELECTION MODE
    var lastselectedcell=null;
    var selectedCells=new Array();
    function startSelectionMode(){
        $('#wordoutput').show(1000);
        setSelectableCells();
        $('.cellsel').live('click',function(){
            if(isAdjacent($(this),lastselectedcell)){
                $('#finalword').text($('#finalword').text()+($(this).text()));
                disableCell($(this));
                lastselectedcell=$(this);
                selectedCells.push(lastselectedcell.attr('id'));
            }
        });
    }

    //Called every X ms to check the turn availability
    function afterWait(){
        console.log("ENTRË ICI");
        $.getJSON("/game", {id : room_number, req : "get_current_player"},function(data){
            gamestate=(data.name==player);
            console.log("The current player is "+data.name);});
        $.getJSON("/game", {id : room_number, req : "get_game_started"},function(data){
            if(data.gameStarted)    $('#waitmsg').text("Please wait, your turn is coming...");
        });
        //WE CHECK IF THE GAME IS OVER, STOP Refreshing
        $.getJSON("/game", {id : room_number, req : "get_game_finished"},function(data){
            if(data.gameFinished)    {
                $('#waitmsg').text("Game is over!");
                clearInterval(intervalID);
            }
        });
        if(gamestate) {
            if(firstTime){
                //  GET PLAYER2 NAME
                var playerJS1,playerJS2;
                $.getJSON("/game", {id : room_number, req : "get_players"},function(data){
                    playerJS1=data.player1;playerJS2=data.player2;
                    if(playerJS1 !=player){player2=playerJS1;
                    }else{player2=playerJS2;}
                    $('#player2').text(player2);
                    console.log(player2+ "is gamer2");
                });
                firstTime=false;
            }else{
                clearInterval(intervalID);
                initgame();
            }
        }else{
            disableTable();
        }
    }
    // POLL SERVER EVERY 3seconds FOR PERMISSION TO TURN START
    var firstTime=true;
    var intervalID;
    function waitUntilGameStart(){
          if(!gamestate){
              intervalID=setInterval(function(){afterWait()},3000);
          }
    }
    //CALLED TO SKIP THE TURN
    function skipTurn(){
        $.post("/game", { id : room_number, req : "skip_player" });
        finishTurn();
    }

    // WILL BE CALLED WHEN SEND WORD BUTTON IS CLICKED
    function playTurn(){
        var correct=true;
        // send word to server
        var word = $('#finalword').text();
        console.log(word);console.log(lastEditedCell.text()); console.log(getX(lastEditedCell));console.log(" " +getY(lastEditedCell));
        // AFTER SENDING THE WORD CHECK IF IT'S LOCALLY CORRECT
        console.log(selectedCells);console.log(lastEditedCell);
        correct= $.inArray(lastEditedCell.attr('id'),selectedCells);
        //console.log(lastEditedCell);console.log(selectedCells);
        console.log(correct);
        if(correct>-1){
            var res = $.post("/game", {id : room_number, req : "play_word", player_name:player, letter:lastEditedCell.text().toLowerCase(), x:getX(lastEditedCell), y:getY(lastEditedCell), word:word.toLowerCase()});
            // AFTER SENDING THE WORD CHECK IF IT'S CORRECT OR NOT USED ALREADY
            var test;
            $.getJSON("/game", {id : room_number, req : "is_valid_word",word:word.toLowerCase()},function(is){
                test=is.word_valid;});
            if(!test){
                $('#errormsg2').text("The chosen word doesn't exist or is already used!");
                lastEditedCell.text("");
            }
            finishTurn();
        }else{ //LOCALLY INCORRECT WORD
            $('#errormsg1').text("The letter you put must be in your word!");//complete msg
            $('#finalword').text("");
            setSelectableCells();
            lastselectedcell=null;
        }
    }
    // WHEN TURN FINALLY FINISHED, for clearing state of player
    function finishTurn(){
        lastEditedCell=null;
        gamestate=false;
        $.getJSON("/game", {id : room_number, req : "get_player",player_name:player},function(pl){
            $("#score1").text(pl.score);});
        $('#waitmsg').text("Please wait, your turn is coming...");
        $('#skip').hide(1000);
        $('#finalword').text("");
        $('#wordoutput').hide(1000);
        $('#errormsg1').text("");
        $('#wait').show(2000);
        waitUntilGameStart();
    }
    //--------------- UTILS FOR CELLS ---------------
    function isAdjacent(a,b){
        //TRUE IF A OR B ARE NULL
        if(a==null || b==null)return a!=b;
        else{
            var xa = getX(a);var ya = getY(a);
            var xb = getX(b);var yb = getY(b);
            //TRUE IF A AND B ARE ADJACENTS
            if(xa==xb) return Math.abs(ya-yb)==1;
            else if(ya==yb) return Math.abs(xa-xb)==1;
            else return false;
        }
    }

    function getX(cell){
        return cell.attr('id')[0];
    }
    function getY(cell){
        return cell.attr('id')[1];
    }

    //SET CELLS TO BE SELECTABLES TO BE PART OF A WORD
    function setSelectableCells(){
        $('.cellen').removeClass('cellen').addClass('celldis');
        $('.celldis').each(function(){
            if($(this).text()!=" "){
                $(this).removeClass('celldis').addClass('cellsel');
            }
            });
    }

    //-----------------------------------------------------------------------------------------------------------------------
    //-------------------------------------------------------- END ---------------------------------------------------//
    /////////////// ------------------- MAIN EXECUTION ---------------/////////////////
    var lastEditedCell=null;
    var player2;
    // false FOR UNSTARTED GAME, true FOR ACTIVE GAME
    var gamestate = false;
   // Log the player to a room to start a new game 
   var room_number = 1;
   $.post("/game", { id : room_number, req : "new_game" });

    // ASK FOR NAME AND SEND IT TO SERVER
   var player= prompt("Enter your player name :");
   while(player=="" || player==null){
       player= prompt("Enter a valid player name please :");
   }
   $('#player1').text(player);
    // send name to server +1 player
    $.post("/game", {id : room_number, req : "add_player", player_name : player})
    // CREATES A WAITING MESSAGE
        $('<p id="waitmsg">Hi '+player+', we are waiting for other players to launch the game!</p>').insertBefore($("img.loading"));
        $("#wait").show(1000,function(){ rendertable();waitUntilGameStart();});




});